#! py -3
# coding:utf-8

import numpy as np
import matplotlib.pyplot as plt
import csv


def mynorm1d(data):
    min = data[0]
    max = data[0]
    for v in data:
        if min > v:
            min = v
        if max < v:
            max = v

    delta = max - min
    for i, v in enumerate(data):
        data[i] = (v - min) / delta


f = open('act_measure.csv', 'r')
csvreader = csv.reader(f)

# for row in csvreader:
#     row: str
#     print(float(row[0]))


indata = [float(row[0]) for row in csvreader]
f.close()

# plt.plot(indata)
# plt.show()

cycle_step = 100  # 输入数据 一个周期的点数
total_cycle = 50  # 输入数据 总共周期数

avg_indata = [0] * cycle_step
for j in range(total_cycle):
    for i in range(cycle_step):
        avg_indata[i] = indata[cycle_step * j + i] + avg_indata[i]

# plt.plot(avg_indata)
# plt.show()

mynorm1d(avg_indata)

max = avg_indata[0]
maxi = 0
for i, v in enumerate(avg_indata):
    if v > max:
        max = v
        maxi = i
print('相移前最大值在原始数据索引位置=', maxi)

# 对原当输入数据进行相移
phase_shift = len(avg_indata) // 2 - 1 - maxi

if phase_shift > 0:
    avg_indata = avg_indata[-phase_shift:] + avg_indata[0:len(avg_indata) - phase_shift]
elif phase_shift < 0:
    avg_indata = avg_indata[-phase_shift:] + avg_indata[0:0 - phase_shift]

max = avg_indata[0]
maxi = 0
for i, v in enumerate(avg_indata):
    if v > max:
        max = v
        maxi = i
print('相移后最大值在原始数据索引位置=', maxi)

# 插值成更多个数据点
req_dcnt = 4000
x = np.array(range(req_dcnt)) / (req_dcnt - 1)
x = x * (len(avg_indata) - 1)
avg_indata = np.interp(x, range(len(avg_indata)), avg_indata) * (req_dcnt // 2)

# plt.plot(avg_indata)
# plt.show()

out_data = [int((len(avg_indata) // 2 - 1) * (i / (len(avg_indata) // 2 - 1))) for i in range(len(avg_indata) // 2)]
out_data = out_data + out_data[::-1]

for j in range(1, len(avg_indata) // 2):
    for i in range(int(out_data[j - 1]), len(avg_indata) // 2 - 1):
        if avg_indata[i + 1] <= out_data[j] <= avg_indata[i] or avg_indata[i] <= out_data[j] <= avg_indata[i + 1]:
            s = avg_indata[i]
            e = avg_indata[i + 1]
            u = (out_data[j] - s) / (e - s)
            if i + u >= out_data[j - 1]:
                out_data[j] = i + u
                break
            elif i == (len(avg_indata) // 2 - 1):
                out_data[j] = out_data[j - 1]

for j in range(len(avg_indata) // 2, len(avg_indata)):
    for i in range(int(out_data[j - 1]), len(avg_indata) - 1):
        if avg_indata[i + 1] <= out_data[j] <= avg_indata[i] or avg_indata[i] <= out_data[j] <= avg_indata[i + 1]:
            s = avg_indata[i]
            e = avg_indata[i + 1]
            u = (out_data[j] - s) / (e - s)
            k = (len(avg_indata) - 1) - (i + u)
            if k <= out_data[j - 1]:
                out_data[j] = k
                break
            elif i == (len(avg_indata) - 2):
                out_data[j] = out_data[j - 1]

out_data[-1] = 0
# plt.plot(out_data)
# plt.show()

revised_data = [0.0] * len(avg_indata)
for i in range(len(revised_data)):
    if i < len(revised_data) // 2:
        index = int(out_data[i])
    else:
        index = int(len(revised_data) - 1 - out_data[i])

    if index >= (len(revised_data) - 1):
        index = len(revised_data) - 1
    if index < 0:
        index = 0

    if i < len(revised_data) // 2:
        u = out_data[i] - index
    else:
        u = len(revised_data) - 1 - out_data[i] - index

    next = index + 1
    if next >= (len(avg_indata)):
        next = index
    v = avg_indata[index] * (1 - u) + avg_indata[next] * u
    revised_data[i] = v

# plt.plot(revised_data)
# plt.show()

# 写输出 csv文件

f = open('revise_out.csv', 'w', newline='')
writer_csv = csv.writer(f, dialect='excel')
for v in out_data:
    writer_csv.writerow([v])

writer_csv = None
f.flush()
f.close()

# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

plt.figure()
plt.subplot(311)
plt.title("输入数据波形")
plt.plot(avg_indata)
plt.tight_layout()  # 调整子图间 间隔

plt.subplot(312)
plt.title("修正的输出数据波形")
plt.plot(out_data)
plt.tight_layout()

plt.subplot(313)
plt.title("输入数据被修正后的波形")
plt.plot(revised_data)
plt.tight_layout()

plt.show()
